package com.zxy.utils;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBCPUtil {
    private static Properties properties = new Properties();
    private static DataSource dataSource;
    //加载DBCP配置文件
    static{
        try{
            String configPath = DBCPUtil.class.getClassLoader().getResource("dbcp.properties").toString().replace("file:/","/");
            FileInputStream is = new FileInputStream(configPath);
            properties.load(is);
        }catch(IOException e){
            e.printStackTrace();
        }
        
        try{
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static DataSource getDataSource() {
        return dataSource;
    }
    
    //从连接池中获取一个连接
    public static Connection getConnection(){
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
        }catch(SQLException e){
            e.printStackTrace();
        }
        //try {
        //    connection.setAutoCommit(false);
        //} catch (SQLException e) {
        //    e.printStackTrace();
        //}
        return connection;
    }
}
